package com.zjj.disk.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjj.disk.pojo.BookKeeping;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Date;

@Repository
public interface BookKeepingMapper extends BaseMapper<BookKeeping> {
    default IPage<BookKeeping> getBookKeepingByConditions(
            @Param("project") String project,
            @Param("type") String type,
            @Param("currentPage") int currentPage,
            @Param("pageSize") int pageSize) {

        Page<BookKeeping> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<BookKeeping> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(project != null, BookKeeping::getProject, project)
                .eq(type != null, BookKeeping::getType, type);

        return this.selectPage(page, queryWrapper);
    }


    /**
     * 获取本年度最高收入记录。
     *
     * @param startOfYear 年初日期
     * @param endOfYear   年末日期
     * @return 最高收入记录
     */
    @Select("SELECT * FROM tbl_book_keeping WHERE type = 'income' AND time >= #{startOfYear} AND time < #{endOfYear} ORDER BY amount DESC LIMIT 1")
    BookKeeping getMaxAmountCurrentYear(Date startOfYear, Date endOfYear);


    /**
     * 获取历史最高收入记录。
     *
     * @return 最高收入记录
     */
    @Select("SELECT * FROM tbl_book_keeping WHERE type = 'income' ORDER BY amount DESC LIMIT 1")
    BookKeeping getMaxAmountHistorical();


    /**
     * 获取历史最高支出记录。
     *
     * @return 最高支出记录
     */
    @Select("SELECT * FROM tbl_book_keeping WHERE type = 'expenditure' ORDER BY amount DESC LIMIT 1")
    BookKeeping getMaxAmountExpense();


    /**
     * 获取历史最高收入记录。
     *
     * @return 最高收入记录
     */
    @Select("SELECT * FROM tbl_book_keeping WHERE type = 'income' ORDER BY amount DESC LIMIT 1")
    BookKeeping getMaxAmountIncome();

    /**
     * 获取当前月份的总收入。
     *
     * @param startOfMonth 月初日期
     * @param endOfMonth   月末日期
     * @return 总收入
     */
    @Select("SELECT COALESCE(SUM(amount), 0) AS total_income FROM tbl_book_keeping WHERE type = 'income' AND time >= #{startOfMonth} AND time < #{endOfMonth}")
    BigDecimal getTotalIncomeCurrentMonth(Date startOfMonth, Date endOfMonth);

    /**
     * 获取当前月份的总支出。
     *
     * @param startOfMonth 月初日期
     * @param endOfMonth   月末日期
     * @return 总支出
     */
    @Select("SELECT COALESCE(SUM(amount), 0) AS total_expense FROM tbl_book_keeping WHERE type = 'expenditure' AND time >= #{startOfMonth} AND time < #{endOfMonth}")
    BigDecimal getTotalExpenseCurrentMonth(Date startOfMonth, Date endOfMonth);
}
